const fs = require('fs');
const path = require('path');
const express = require('express');
const waterfall = require('async-waterfall');

const router = express.Router();
const base = './db/';

const format = () => {
  const _d = new Date();
  const y = _d.getFullYear();
  const m = _d.getMonth() + 1;
  const d = _d.getDate();
  return {
    ym : [y, m].join('-'),
    ymd: [y, m, d].join('-'),
  };
};
router.post('/add', (req, res) => {
  let { content } = req.body;
  if (!content) {
    const err = 'empty content..';
    res.send({code : -1, err});
    return;
  }
  content = JSON.parse(content);

  const timestamp = Date.now();
  const entry = { timestamp, content };
  const pathname = path.join(base, format().ymd +'.json');
  waterfall([
    cb => {
      fs.stat(pathname, (err, rs) => {
        cb(null, err ? false : rs.isFile());
      });
    },
    (isFile, cb) => {
      if (isFile) { cb(null); return; }
      fs.writeFile(pathname, '[]', err => {
        if (err) { cb(err); return; }
        cb(null);
      });
    },
    cb => {
      fs.readFile(pathname, (err, rs) => {
        if (err) { cb(err); return; }
        cb(null, JSON.parse(rs.toString()));
      });
    },
    (arr, cb) => {
      arr = [entry, ...arr];
      const str = JSON.stringify(arr, null, 2);
      fs.writeFile(pathname, str, err => {
        if (err) { cb(err); return; }
        cb();
      });
    }
  ], (err, rs) => {
    res.send(err ? {code : -1, err} : {code : 0});
  });
});
router.get('/get', (req, res) => {
  const { year, month, date } = req.query;
  const filename = year +'-'+ month +'-'+ date +'.json';
  const pathname = path.join(base, filename);
  waterfall([
    cb => {
      fs.stat(pathname, (err, rs) => {
        if (err) { cb(err); return; }
        if (!rs.isFile()) { cb(err); return; }
        cb(null);
      });
    },
    cb => {
      fs.readFile(pathname, (err, rs) => {
        if (err) { cb(err); return; }
        cb(null, JSON.parse(rs.toString()));
      });
    }
  ], (err, rs) => {
    res.send(err ? {code : -1, err} : {code : 0, rs});
  });
});

module.exports = router;
